package com.zhitong.ztblog.aop;

import com.zhitong.ztblog.entity.Blog;
import com.zhitong.ztblog.entity.Log;
import com.zhitong.ztblog.services.IBlogService;
import com.zhitong.ztblog.services.ILogService;
import com.zhitong.ztblog.services.IUserService;
import com.zhitong.ztblog.utils.DateUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
public class BlogAop {

    @Autowired
    private ILogService logService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IBlogService blogService;

    //插入博客时,增加日志
    @Pointcut("execution(public * com.zhitong.ztblog.services.servicesImp.BlogService.insertBlog(..))")
    public void insertBlog(){};

    //删除博客时,增加日志
    @Pointcut("execution(public * com.zhitong.ztblog.services.servicesImp.BlogService.delBlogById(..))")
    public void delBlog(){};

    //修改博客时,增加日志
    @Pointcut("execution(public * com.zhitong.ztblog.services.servicesImp.BlogService.updateBlog(..))")
    public void updateLog(){};

    @After("insertBlog()")
    public void addInsertLog(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        Blog blog=(Blog)args[0];
        Log log=new Log();
        log.setName("发布了新的博客:"+blog.getTitle());
        log.setTime(new Date());
        log.setNickName(userService.findById(blog.getUid()).getNickName());
        logService.insertLog(log);
    }

    @Before("delBlog()")
    public void addDelLog(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        int id=(int)args[0];
        Blog byId = blogService.findById(id);
        Log log=new Log();
        log.setName("下架了博客:"+byId.getTitle());
        log.setTime(new Date());
        log.setNickName(byId.getUser().getNickName());
        logService.insertLog(log);
    }

    @Before("updateLog()")
    public void updateLog(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        Blog blog =(Blog)args[0];
        blog.setLastTime(new Date());
        Log log=new Log();
        log.setName("更新了博客:"+blog.getTitle());
        log.setTime(new Date());
        log.setNickName(blog.getUser().getNickName());
        logService.insertLog(log);
    }

}
